<?php
/**
*
* 功能描述（设置控制器）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class CtrlConf extends CtrlBase
{
	public $paramCheck = array(
		'modimg' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
			'title' => array('POST', 'must', 'trim', 'notempty'),
			'url' => array('POST', 'must', 'trim', 'notempty'),
			'image' => array('FILES', 'must', '', ''),
			'sort' => array('POST', 'must', 'intval', 'notnegative'),
		),
		'addimg' => array(
			'title' => array('POST', 'must', 'trim', 'notempty'),
			'url' => array('POST', 'must', 'trim', 'notempty'),
			'image' => array('FILES', 'must', '', ''),
			'sort' => array('POST', 'must', 'intval', 'notnegative'),
		),
		'delimg' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
		),
	);
	public $perm = array('cake', "index.php?action=login.tologin");

	function Index()
	{
		$obj = $this->GetModel("conf");
		$this->assign('conf', $obj->GetConf());
		return RT_TPL;
	}

	function DelImg()
	{
		$id = $this->params['id'];
		$obj = $this->GetModel("conf");
		if($obj->ImgCnt() <= 1)
		{
			echo "至少保留一个，可修改不可删除";
			return RT_NONE;
		}
		$cnt = $obj->DelConf($id);
		if($cnt <= 0)
		{
			echo "指定的数据已经不存在";
			return RT_NONE;
		}
		$msg = '删除成功';
		$filename =  WEBDATA_DIR . 'index_img_' . $id . '.jpg';
		//删除图片
		$ret = @unlink($filename);
		$this->CoreLog('conf_del', 0, $ret, 'index_img');
		echo '0';
		return RT_NONE;
	}

	function AddImg()
	{
		$obj = $this->GetModel("conf");
		$file = $this->params['image'];
		if($file['name'] == '')
			return RT_ATTACK;
		$data = array(
			'value' => $this->params['title'],
			'param' => $this->params['url'],
			'sort' => $this->params['sort'],
			'key' => 'index_img',
		);
		$id = $obj->AddConf($data);
		if($id <= 0)
		{
			$this->assign("msg", "添加失败");
			return RT_MSG;
		}
		$this->CoreLog('conf_add', $id, 0, 'index_img');
		$msg = $this->StoreFile($file, $id);
		if($msg != '')
		{
			$this->assign("msg", $msg);
			return RT_MSG;
		}
		jump_to('index.php?action=conf.index', '添加成功');
		return RT_NONE;
	}

	function ModImg()
	{
		$obj = $this->GetModel("conf");
		$file = $this->params['image'];
		$id = $this->params['id'];
		if($file['name'] != '')
		{
			$msg = $this->StoreFile($file, $id);
			if($msg != '')
			{
				$this->assign("msg", $msg);
				return RT_MSG;
			}
		}
		$data = array(
			'value' => $this->params['title'],
			'param' => $this->params['url'],
			'sort' => $this->params['sort'],
		);
		$cnt = $obj->UpdateConf($id, $data);
		$this->CoreLog('conf_mod', $id, 0, 'index_img');
		jump_to('index.php?action=conf.index', '修改成功');
		return RT_NONE;
	}

	private function StoreFile($file, $id)
	{
		$name = 'index_img_' . $id . '.jpg';
		if($file['type'] != 'image/jpeg')
			return "文件类型不支持";
		if($file['size'] > 1024 * 1024 * 100)
			return "文件大小超出限制";
		if($file['error'] > 0)
			return "上传错误";
		$filename = WEBDATA_DIR . $name;
		if(!move_uploaded_file($file['tmp_name'], $filename))
			return "存储错误";
		return '';
	}
}

